// src/auth/auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../users/entities/user.entity';
import { LoginDto } from './dto/login.dto';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private jwtService: JwtService,
  ) {}

  // 登录方法
  async login(loginDto: LoginDto) {
    const user = await this.usersRepository.findOne({
      where: { username: loginDto.username },
      relations: ['roles', 'roles.menus'],
    });

    if (!user || !(await bcrypt.compare(loginDto.password, user.password))) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    const payload = { 
      sub: user.id, 
      username: user.username,
      roles: user.roles.map(role => role.name)
    };

    return {
      access_token: await this.jwtService.signAsync(payload),
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        roles: user.roles,
        menus: this.getUniqueMenus(user.roles),
      },
    };
  }

  // 退出登录方法
  async logout() {
    // 这里可以添加逻辑，例如记录用户的退出时间等
    return { message: 'Logout successful' };
  }

  private getUniqueMenus(roles: any[]) {
    const menuMap = new Map();
    roles.forEach(role => {
      role.menus.forEach(menu => {
        menuMap.set(menu.id, menu);
      });
    });
    return Array.from(menuMap.values());
  }
}